import { instantiate, Prefab } from 'cc';
import { BusyIndicator } from '../../../../../wing/assets/src';
import { app } from '../../application';
import { HintNetBusyInfo } from '../../declarations';
import { ccclass, ccmodifier } from '../../decorators';
import { HintNetBusy } from './HintNetBusy';
import { HintStack } from './HintStack';

/**
 * - 作者: DoooReyn
 * - 日期: 2023.11.02
 * - 名称: HintNetBusyStack
 * - 描述: 网络繁忙提示堆栈
 * - 说明: 网络繁忙提示同时只能显示一个，新的提示会覆盖旧的提示
 * - 注意: 需要先初始化，设置一个模板
 */
@ccclass()
@ccmodifier('HintNetBusyStack')
export class HintNetBusyStack extends HintStack {
    /** 示忙器 */
    protected _busy: BusyIndicator | null;

    /** 当前组件 */
    protected _page: HintNetBusy | null;

    protected onLoad(): void {
        super.onLoad();
        this._busy = new BusyIndicator();
    }

    protected onDestroy(): void {
        this._busy!.clear();
        this._busy = null;
    }

    /**
     * 注册
     * @param cfg 网络繁忙提示配置
     */
    async register(cfg: HintNetBusyInfo) {
        // 如果有正在显示的提示，则需要移除
        if (this._page) {
            this._page.node.destroy();
            this._page = null;
        }

        // 添加提示
        const prefab = await app.resLoader.loadOne({ path: cfg.path, bundle: cfg.bundle, type: Prefab });
        if (prefab && prefab.data.getComponent(HintNetBusy)) {
            const node = instantiate(prefab);
            this.node.addChild(node);
            this._page = node.getComponent(HintNetBusy)!;
            await this.hide();
        }
    }

    /** 增加次数 */
    increase() {
        this._busy?.increase();
    }

    /** 减少次数 */
    decrease() {
        this._busy?.decrease();
    }

    protected get interactable() {
        return this._busy?.busy || false;
    }

    /** 次数变化时调用 */
    async onUpdate() {
        if (this._busy?.busy) {
            await this.show();
            await this._page?.show();
        } else {
            await this._page?.hide();
            await this.hide();
        }
    }

    async enter(): Promise<void> {
        this._busy?.add(this);
        this.onCheckInteractable();
        this.logger.debug('进入舞台');
    }

    async exit() {
        this._busy?.remove(this);
        this._busy?.reset();
        await super.exit();
    }
}
